import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { Message } from 'src/app/models/message';
import { BaseService, DataRegisterService } from 'src/app/services';
import { EventManagerService } from 'src/app/services/event-manager.service';
import { IMessageQueryParams, MessageService } from 'src/app/services/message.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { UploadService } from 'src/app/services/upload.service';
import { EngineService } from '../../../services/engine.service';
import { BaseFieldComponent } from '../base-field/base-field.component';

@Component({
  selector: 'zepride-task-notification',
  templateUrl: './task-notification.component.html',
  styleUrls: ['./task-notification.component.less']
})
export class TaskNotificationComponent extends BaseFieldComponent implements OnInit {

  messages: Message[] = [];
  taskMsg: any;
  notificationMsg: any;
  taskWarning: any;
  taskMessages: Message[] = [];
  notificationMessages: Message[] = [];
  taskWarningMessages: Message[] = [];

  constructor(
    protected engineService: EngineService,
    protected baseSvr: BaseService,
    protected eventSvr: EventManagerService,
    protected orgSvr: OrganizationService,
    public uploadService: UploadService,
    protected msg: NzMessageService,
    private messageService: MessageService,
    protected dataRegisterService: DataRegisterService
  ) {
    super(engineService, baseSvr, eventSvr, orgSvr, uploadService, msg, dataRegisterService);
  }

  async ngOnInit() {
    try {
      this.getPageData();
      this.messages = await this.getMessageData();
      this.groupMessageByType(this.messages);
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  groupMessageByType(messages: Message[]) {
    this.taskMessages = messages.filter(msg => msg.type === 'taskMsg');
    this.notificationMessages = messages.filter(msg => msg.type === 'notificationMsg');
    this.taskWarningMessages = messages.filter(msg => msg.type === 'taskWarning');
  }

  getMessageData() {
    const orgId = localStorage.getItem('orgid');
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const params: IMessageQueryParams = {
      orgId,
      receiverIds: [userInfo.id]
    };
    return this.messageService.queryMessages(params);
  }

  getPageData() {
    if (this.componentData.extends && this.componentData.extends.redirectPages) {
      const redirectPages = this.componentData.extends.redirectPages;
      this.taskMsg = redirectPages.taskMsg;
      this.notificationMsg = redirectPages.notificationMsg;
      this.taskWarning = redirectPages.taskWarning;
    }
  }

}
